package com.aoyama.juc._06_block;

/**
 * @author ：qs
 * @date ：Created in 2022/7/18
 * @description：
 * @modified By：
 *
 *  功能描述: 功能描述: 4个线程的if语句
 *  要求:生产者线程消费一个,消费者线程消费一个。num只能为1或0
 *  改用while循环的4个线程
 */
public class ProducerDemo1 {
    public static void main(String[] args) {
        Consumer3 consumer = new Consumer3();

        //生产者线程A
        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    consumer.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者A").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    consumer.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者B").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    consumer.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者C").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    consumer.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者D").start();
    }
}
class Consumer3{
    private Integer num = 0;

    public synchronized void increment() throws InterruptedException {
        while(num != 0){
            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName() + "\t" + num);
        notifyAll();

    }

    public synchronized void decrement() throws InterruptedException {
        while(num == 0){
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName() + "\t" + num);
        notifyAll();
    }

}